﻿using Qy.Core;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading.Tasks;

namespace Qy.Scenario;

[AppService]
public class ContentCateService : QyRepository<ContentCate>
{
    private readonly UserDeptService _UserDeptService;
    public ContentCateService(
        UserDeptService adminUserDeptService, ApplicationContext applicationContext) : base(applicationContext)
    {
        _UserDeptService = adminUserDeptService;
    }

    /// <summary>
    /// 全部列表并缓存
    /// </summary>
    /// <returns></returns>
    public async Task<List<ContentCate>> GetAllCacheAsync()
    {
        return await GetAllListAsync("Sort asc");
    }

    /// <summary>
    /// 根据权限获取栏目列表
    /// </summary>
    /// <param name="cid"></param>
    /// <returns></returns>
    public async Task<List<ContentCate>> CateRoleListAsync(IEnumerable<int> cids)
    {
        List<ContentCate> cates = await GetAllCacheAsync();
        List<ContentCate> newCates = new();
        foreach (int cid in cids)
        {
            ContentCate cate = new();
            cate = cates.FirstOrDefault(o => o.Id == cid && o.Status == true);
            if (cate != null)
                newCates.Add(cate);
        }
        return newCates;
    }

    public async Task<bool> Delete(int id)
    {
        bool get = await Context.Queryable<Content>()
               .Where(content => content.Cid == id)
               .AnyAsync();
        if (get) 
            return await DeleteAndDelCacheAsync(id) > 0;
        return get;
    }

    /// <summary>
    /// 输出JSON 树形栏目列表
    /// </summary>
    /// <returns></returns>

    public async Task<IEnumerable<CategoryViewModel>> GetCatTree(ILoginUserInfo user)
    {
        List<ContentCate> cates;
        if (user.GroupId != 1)
        {
            IEnumerable<int> cateIdChannl = await GetRoleChannlAsync(user.DeptId);
            cates = await CateRoleListAsync(cateIdChannl);
        }
        else cates = await GetAllCacheAsync();
        cates = cates.Where(x => x.Status == true).ToList();
        List<CategoryViewModel> treeModels = new();
        var cateModels = cates.AsViewCategoryModels();
        CategoryExtensions.IndentedContentCates(cateModels, treeModels);
        return treeModels;
    }


    //获取当前用户部门的栏目权限信息
    public async Task<IEnumerable<int>> GetRoleChannlAsync(int deptId)
    {
        UserDept userDept = await _UserDeptService.GetInfo(deptId);
        try
        {
            return JsonSerializer.Deserialize<IEnumerable<int>>(userDept.ContentCateRole);
        }
        catch (Exception e)
        {
            Console.WriteLine("获取部门栏目权限信息错误：" + e.Message);
            return null;
        }
    }

    public async Task<IEnumerable<CategoryViewModel>> GetContentCateListAsync(ILoginUserInfo user)
    {
        List<ContentCate> cates;
        if (user.GroupId != 1)
        {
            IEnumerable<int> cateIdChannl = await GetRoleChannlAsync(user.DeptId);
            cates = await CateRoleListAsync(cateIdChannl);
        }
        else cates = await GetAllCacheAsync();
        cates = cates.Where(x => x.Status == true).ToList();
        return cates.AsCateListItems();
    }

    /// <summary>
    /// 栏目管理列表
    /// </summary>
    /// <returns></returns>
    public async Task<IEnumerable<ContentCatViewModel>> GetContentCates()
    {
        return await GetCates(0, await GetAllCacheAsync());
    }

    /// <summary>
    /// 递归栏目树
    /// </summary>
    /// <param name="pid">父级Id</param>
    /// <param name="cates">数据源</param>
    /// <returns></returns>
    private async Task<List<ContentCatViewModel>> GetCates(int pid, List<ContentCate> cates = null)
    {
        var parent = cates.Where(P => P.Pid == pid);
        List<ContentCatViewModel> lists = new();
        foreach (var item in parent)
        {
            ContentCatViewModel Childer = new()
            {
                Id = item.Id,
                Title = item.Name,
                Type = item.Type,
                Theme = item.Theme,
                Ctheme = item.Ctheme,
                Ico = item.Ico,
                Sort = item.Sort,
                Num = item.Num,
                Status = item.Status
            };
            Childer.Children = await GetSon(Childer, cates);
            lists.Add(Childer);
        }
        async Task<List<ContentCatViewModel>> GetSon(ContentCatViewModel cates, List<ContentCate> sonCates = null)
        {
            if (!sonCates.Exists(x => x.Pid == cates.Id))
                return null;
            else
                return await GetCates(cates.Id, sonCates);
        }
        return lists.OrderBy(o => o.Sort).ThenBy(o => o.Id).ToList();
    }



    #region 前台用

    /// <summary>
    /// 根据 CID 获取 一条栏目数据
    /// </summary>
    /// <returns></returns>
    public async Task<ContentCate> GetOneAsync(int cid)
    {
        List<ContentCate> cates = await GetAllCacheAsync();
        return cates?.FirstOrDefault(a => a.Id == cid);
    }

    /// <summary>
    /// 获取指定栏目列表
    /// </summary>
    /// <param name="cids"></param>
    /// <returns></returns>
    public async Task<IEnumerable<ContentCate>> CateListByIdAsync(int[] cids)
    {
        IEnumerable<ContentCate> cats = await GetAllCacheAsync();
        var x = cats?.Where(o => cids.Contains(o.Id)).OrderBy(o => o.Sort);
        return x;
    }

    /// <summary>
    /// 获取子栏目Ids
    /// </summary>
    /// <param name="pid"></param>
    /// <returns></returns>
    public async Task<int[]> CatSonListIdsAsync(int pid)
    {
        IEnumerable<ContentCate> cats = await GetAllCacheAsync();
        IEnumerable<ContentCate> sonCats = cats.Where(o => o.Pid == pid).OrderBy(o => o.Sort);
        return sonCats.Select(o => o.Id).ToArray();
    }

    #endregion
}
